﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Cmd;
using GameData;
using TNet;
using Random = UnityEngine.Random;

public class GlobalComponet : MonoBehaviour
{

    public int serverTcpPort = 5127;
    public string[] serverList;

    string mAddress = "127.0.0.1";
    string mMessage = "";
    float mAlpha = 0f;

    private HeartbeatSend heartbeat;

    //
    public GameObject preDisconnect;


    private bool isInit = false;


    public void init()
    {
        if (isInit)
        {
            return;
        }
        isInit = true;
        S2C_NumberCountInfo.CallBackDic.Add("SC统计数据", OnUpdateNumAllInfo);

        S2C_PickNumInfo.CallBackDic.Add("SC抽号", OnPickNumInfo);

        S2C_PickAllInfo.CallBackDic.Add("SC排号信息", OnPickAllInfo);

        S2C_DueNumbers.CallBackDic.Add("SC处理名单", OnDueNumbers);

        S2C_CallNumber.CallBackDic.Add("SC叫号", OnCallNumber);

        S2C_RecAndVIPNum.CallBackDic.Add("SC取号和VIP信息", RecAndVipNum);

        S2C_SetSoundType.CallBackDic.Add("SC设置语种", SetSoundType);

        S2C_SetRecType.CallBackDic.Add("SC设置取号方式", SetRecType);

        S2C_SetDataInfo.CallBackDic.Add("SC设置数据", SetDataInfoResponse);

        S2C_PickQueueNum.CallBackDic.Add("SC队列信息", UpdatePickQue);

        TNAutoJoin.instance.OnConnectingAction = OnConnectingAction;
        TNAutoJoin.instance.OnDisconnectAction = OnDisconnectAction;

        heartbeat = new HeartbeatSend();
        //
        Messenger.AddListener("重连服务器", OnReConnect);

        //心跳
        InvokeRepeating("Heartbeat", 10, 10F);
    }

    void UpdatePickQue(PickNumInfo pickNumInfo)
    {

        GlobalVO.GetInstance().PickNumInfo = pickNumInfo;
        GlobalVO.GetInstance().NumAllInfo.PickNumInfo = pickNumInfo;
        Debug.Log("收到队列信息:是否完成:" + pickNumInfo.isComplete);
        Messenger.Broadcast("SC队列信息", MessengerMode.DONT_REQUIRE_LISTENER);

    }


    void SetDataInfoResponse(SetDataInfoDic SetDataInfoDic)
    {
        Debug.Log("SC设置数据啦啊啊啊啊啊啊");
        GlobalVO.GetInstance().NumAllInfo.SetDataDic = SetDataInfoDic.SetDataDic;
        Messenger<Dictionary<string, string>>.Broadcast("SC设置数据", SetDataInfoDic.SetDataDic,
            MessengerMode.DONT_REQUIRE_LISTENER);

    }

    void SetRecType(RecNumType recNumType)
    {

        GlobalVO.GetInstance().NumAllInfo.isRecIdCard = recNumType.reNumType;
        Messenger<bool>.Broadcast("SC设置取号方式", recNumType.reNumType, MessengerMode.DONT_REQUIRE_LISTENER);


    }


    void SetSoundType(SoundType soundType)
    {
        GlobalVO.GetInstance().SoundType = soundType;
        Messenger<SoundType>.Broadcast("SC设置语种", soundType, MessengerMode.DONT_REQUIRE_LISTENER);

    }

    void RecAndVipNum(NumListData numListData)
    {

        Messenger<NumListData>.Broadcast("SC取号和VIP信息", numListData, MessengerMode.DONT_REQUIRE_LISTENER);


    }

    void OnCallNumber(CallNumber callNumber)
    {
        Messenger<CallNumber>.Broadcast("SC叫号", callNumber, MessengerMode.DONT_REQUIRE_LISTENER);

    }

    void Start()
    {
        if (Application.isPlaying)
        {
            Screen.sleepTimeout = SleepTimeout.NeverSleep;
            Tools.ResolveIPs(null);
            TNManager.StartUDP(Random.Range(10000, 50000));
            Application.runInBackground = true;

        }

    }


    void OnDueNumbers(DueNuminfos dueNuminfos)
    {
        GlobalVO.GetInstance().dueNuminfos = dueNuminfos;
        Debug.Log("收到处理名单:" + GlobalVO.GetInstance().dueNuminfos.NumberInfoList.Count);
        Messenger<DueNuminfos>.Broadcast("SC处理名单", dueNuminfos, MessengerMode.DONT_REQUIRE_LISTENER);

    }

    //断线重连机制
    public DateTime SendTime;
    public bool isSend = false;

    void Heartbeat()
    {
        //
        if (GlobalVO.GetInstance().roleInfo != null)
        {

            if (isSend)
            {
                //已经发送
                DateTime dt = DateTime.Now;
                TimeSpan ts = dt - SendTime;

                if (ts.Seconds > 2)
                {
                    //断线无反应

                    //
                    TNManager.Disconnect();
                    TNAutoJoin.instance.Connect();

                }

            }
            else
            {
                SendTime = DateTime.Now;
                heartbeat.Send(GlobalVO.GetInstance().roleInfo.UserInfo, HeartBeatResponse);
                isSend = true;
            }


        }
    }

    void HeartBeatResponse(NumAllInfo info)
    {
        isSend = false;
        OnUpdateNumAllInfo(info);
    }




    void OnUpdateNumAllInfo(NumAllInfo info)
    {
        Debug.Log("推送-SC统计数据");
        GlobalVO.GetInstance().NumAllInfo = info;
        GlobalVO.GetInstance().PickNumInfo = info.PickNumInfo;
        Messenger<NumAllInfo>.Broadcast("SC统计数据", info, MessengerMode.DONT_REQUIRE_LISTENER);

    }




    void OnPickAllInfo(PickAllNumInfo pickAllNumInfo)
    {
        GlobalVO.GetInstance().PickAllNumInfo = pickAllNumInfo;
        GlobalVO.GetInstance().PickAllNumInfo.NumberInfoList.Sort(SortCompare);
        Debug.Log("推送-获取到所有排号信息");
        Messenger<PickAllNumInfo>.Broadcast("SC排号信息", pickAllNumInfo, MessengerMode.DONT_REQUIRE_LISTENER);


    }

    public static int SortCompare(NumberInfo AF1, NumberInfo AF2)
    {
        int res = 0;
        if (AF1.QueueNum > AF2.QueueNum)
        {
            res = 1;
        }
        else if (AF1.QueueNum < AF2.QueueNum)
        {
            res = -1;
        }
        return res;
    }




    void OnPickNumInfo(PickNumInfo pickNumInfo)
    {
        Debug.Log("抽取号码啦：数量：" + pickNumInfo.NumberInfoList.Count);
        Messenger<PickNumInfo>.Broadcast("SC抽号", pickNumInfo, MessengerMode.DONT_REQUIRE_LISTENER);
    }

    void Update()
    {

        if (Application.isPlaying)
        {
            float target = (TNLobbyClient.knownServers.list.size == 0) ? 0f : 1f;
            if (TNLobbyClient.knownServers.list.size > 0)
            {
                Debug.Log("aa:" + TNLobbyClient.knownServers.list.size);
            }
            mAlpha = UnityTools.SpringLerp(mAlpha, target, 8f, Time.deltaTime);
        }

    }


    void OnConnectingAction(bool res)
    {
        GlobalVO.GetInstance().isConnecting = res;
        if (res)
        {
            isSend = false;
        }
    }

    public GameObject disconObj;

    void OnDisconnectAction()
    {
        GlobalVO.GetInstance().isConnecting = false;
        //监听到断线
         disconObj = GameObject.Instantiate(preDisconnect);
        GameObject ui = GameObject.Find("UI");
        if (ui != null)
        {
            disconObj.transform.SetParent(ui.transform, false);
            disconObj.transform.SetAsLastSibling();
        }
    }

    public void OnReConnect()
    {
        if (disconObj!= null)
        {
            GameObject.DestroyImmediate(disconObj);
            disconObj = null;
        }

    }

}
